//
//  VipViewController.m
//  TQY
//
//  Created by 甘世清 on 2024/10/18.
//

#import "VipViewController.h"
#import <RMStore/RMStore.h>
#import "VipModel.h"
#import "VipTypeCollectionViewCell.h"
#import "ViptypeView.h"
@interface VipViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic , strong) HeaderView * headerView;
@property (nonatomic , strong) UILabel * nameLabel;
@property (nonatomic , strong) VipModel * seletedModel;
@property (nonatomic , strong) SQCustomButton * btn;
@end

@implementation VipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.zx_backBtnImageName = @"返回 1";
    self.zx_navTitle = SQNSLocalString(@"VIP会员");
    [self zx_setRightBtnWithText:SQNSLocalString(@"恢复购买") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [YJProgressHUD SQ_showMsgWithoutView:@""];
       [[RMStore defaultStore] restoreTransactionsOnSuccess:^(NSArray *transactions) {
             [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"没有购买可以恢复")];
        } failure:^(NSError *error) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"暂无数据")];
        }];
    }];
    self.zx_navBar.zx_rightBtn.zx_fixWidth = 60;
     self.zx_navBar.zx_rightBtn.zx_fixImageSize = CGSizeMake(0, 0);
    self.zx_navBar.zx_rightBtn.titleLabel.font = FONT_REGULAR(14);
    self.zx_navBar.zx_rightBtn.zx_tintColor = SQColor(@"#FF9F00");
    [self SQ_header];
}

- (void)SQ_UIViewForSelfView{
  
    
    UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    scrollView.delegate = self;
    scrollView.contentSize = CGSizeMake(SCREEN_WIDETH, SCREEN_HEIGHT+10);
    scrollView.showsVerticalScrollIndicator = FALSE;
    [self.view addSubview:scrollView];
    scrollView.backgroundColor =  SQColor3DA59D;
    UIView * bgView = [[UIView alloc]init];
    bgView.backgroundColor =  SQColor3DA59D;
    [scrollView addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.top.equalTo(scrollView);
         make.width.mas_equalTo(SCREEN_WIDETH);
        if (SCREEN_HEIGHT > 812) {
            make.height.mas_equalTo(SCREEN_HEIGHT+10);
        } else {
            make.height.mas_equalTo(822);
        }
    }];
    [bgView addSubview:self.headerView];
    [bgView addSubview:self.nameLabel];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(68);
        make.left.equalTo(bgView).offset(20);
        make.top.equalTo(bgView).offset(92);
    }];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgView).offset(100);
        make.top.equalTo(self.headerView).offset(13);
    }];
    UILabel * label2 = [[UILabel alloc]init];
    label2.text = SQNSLocalString(@"开通会员，即可解锁所有特权");
    label2.font  = FONT_MEDIUM(13);
    label2.textColor = SQColor(@"#F3EFFF");
    [bgView addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(100);
            make.top.equalTo(self.headerView).offset(40);
    }];
    UIImageView * vipImageView = [[UIImageView alloc]init];
    vipImageView.image = SQGetImage(@"VIP标志");
    [bgView addSubview:vipImageView];
    [vipImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bgView.mas_right);
        make.top.equalTo(self.headerView).offset(3);
        make.width.mas_equalTo(130);
        make.height.mas_equalTo(63);
    }];
    
    
    UIImageView * bgImageView = [[UIImageView alloc]init];
    bgImageView.image = SQGetImage(@"二级涂层");
    bgImageView.layer.cornerRadius = 30;
    bgImageView.layer.masksToBounds = YES;
    bgImageView.clipsToBounds = YES;
    bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    [bgView addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(bgView);
        make.top.equalTo(bgView).offset(170);
    }];
    
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = flowLayout;
    [self.collectionView registerClass:[VipTypeCollectionViewCell class] forCellWithReuseIdentifier:@"VipTypeCollectionViewCell"];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.alwaysBounceVertical = NO;
    [bgView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(bgImageView);
        make.top.equalTo(bgImageView).offset(10);
        make.height.mas_equalTo(170);
    }];
    ViptypeView * typeView = [[ViptypeView alloc]init];
    typeView.backgroundColor = UIColor.clearColor;
    [bgView addSubview:typeView];
    [typeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(bgView);
        make.top.equalTo(self.collectionView.mas_bottom);
        make.height.mas_equalTo(260);
    }];
    
    [self.view addSubview:self.btn];
    [self.btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(typeView.mas_bottom);
            make.height.mas_equalTo(50);
            make.width.mas_equalTo(SCREEN_WIDETH-80);
    }];
    
    YYLabel * label3 = [[YYLabel alloc]initWithFrame:CGRectZero];
    label3.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    label3.textAlignment = NSTextAlignmentCenter;
    label3.numberOfLines = 0;
    [bgView addSubview:label3];
    NSDictionary *attributes = @{NSFontAttributeName:FONT_MEDIUM(12) , NSForegroundColorAttributeName: SQColor(@"#333333")};
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:SQNSLocalString(@" 点击阅读《自动续费与增值服务协议》,自动续费可随时在iTunes账户设置中取消订阅. 服务到期时前24小时,将从您的付费渠道自动扣费并续期vip权益.") attributes:attributes];
    WS(weakSelf);
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:SQNSLocalString(@"《自动续费与增值服务协议》")] color:SQColor3DA59D backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  @"https://taoqingyan.qingtao.fun/agreement.html?id=3";
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    NSRange range1=[[text string]rangeOfString:SQNSLocalString(@"《自动续费与增值服务协议》")];
    YYTextDecoration* deco=[YYTextDecoration decorationWithStyle:(YYTextLineStyleSingle) width:[NSNumber numberWithInt:0] color:[UIColor whiteColor]];
    [text yy_setTextUnderline:deco range:range1];
    label3.attributedText = text;
    [label3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView);
        make.width.mas_equalTo(SCREEN_WIDETH-80);
        make.top.equalTo(self.btn.mas_bottom).offset(20);
        make.height.mas_equalTo(60);
    }];

    [self.btn setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [weakSelf SQ_buttonClick];
    }];
}

-(void)SQ_header{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [HttpTool post:@"recharge/list" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        [self.jsonArray removeAllObjects];
        NSArray * array = [VipModel mj_objectArrayWithKeyValuesArray:httpModel.data];
        [self.jsonArray addObjectsFromArray:array];
        if (array.count > 0) {
            self.seletedModel = array.firstObject;
            self.seletedModel.isseleted = YES;
            [self SQ_RMStore];
        }
        [self.collectionView reloadData];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.data];
    }];
}
-(void)SQ_RMStore{
    NSMutableArray * array = [[NSMutableArray alloc]init];
    [self.jsonArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        VipModel * model = (VipModel*)obj;
        if ([model.appleId isNotEmpty]) {
            [array addObject:model.appleId];
        }
    }];
     [[RMStore defaultStore] requestProducts:[NSSet setWithArray:array] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
        if([products count] == 0){
            DTLog(@"--------------没有商品------------------");
            return;
        }
        DTLog(@"内购商品列表------%@",products);
    } failure:^(NSError *error) {
        DTLog(@"--------------请求商品失败--------------%@----",error);
    }];
}
-(void)SQ_buttonClick{
    //调用内购
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    WS(weakSelf);
     [[RMStore defaultStore] addPayment:self.seletedModel.appleId success:^(SKPaymentTransaction *transaction) {
            [weakSelf checkIAPResultWithtransactionReceiptblock];
        } failure:^(SKPaymentTransaction *transaction, NSError *error) {
            if (error) {
                NSDictionary * userinfo = error.userInfo;
                [YJProgressHUD showMsgWithoutView: SQNSLocalString([userinfo objectForKey:@"NSLocalizedDescription"])];
            } else {
                [YJProgressHUD showMsgWithoutView: SQNSLocalString(@"交易已取消")];
            }
           
    }];
}
- (void)checkIAPResultWithtransactionReceiptblock
{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        if (receiptURL) {
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
            NSString *encodeStr = [receiptData base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithLineFeed];
             NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:encodeStr forKey:@"certificate"];
             [YJProgressHUD SQ_showMsgWithoutView:@""];
            [HttpTool post:@"recharge/recharge" paramDic:dic successBlock:^(BaseModel * _Nullable httpModel) {
                UserModel * mo = [UserModel share];
                mo.isVip = YES;
                [UserModel updateLocalUserModel:mo];
                [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"购买成功")];
                for (SKPaymentTransaction *aTransaction in [[SKPaymentQueue defaultQueue] transactions]) {
                    [[SKPaymentQueue defaultQueue]finishTransaction:aTransaction];
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self SQ_popViewVC];
                });
            } andFailBloc:^(BaseModel * _Nullable httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
        }else{
            [YJProgressHUD hide];
        }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.jsonArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    VipTypeCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VipTypeCollectionViewCell" forIndexPath:indexPath];
    cell.model = [self.jsonArray objectAtIndex:indexPath.item];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(105, 130);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return  10;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 20, 0, 20);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.seletedModel.isseleted = NO;
    self.seletedModel= [self.jsonArray objectAtIndex:indexPath.item];
    self.seletedModel.isseleted = YES;
    [self.collectionView reloadData];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
 
- (SQCustomButton *)btn{
    if (!_btn) {
        _btn = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(0, 0) midmargin:0];
        _btn.font = FONT_MEDIUM(16);
        _btn.SQBackimageView.image = SQGetImage(@"vip矩形");
        _btn.SQBackimageView.contentMode = UIViewContentModeScaleAspectFill;
        _btn.text = SQNSLocalString(@"立即开通");
        _btn.textColor = SQColor(@"#FFFFFF");
        _btn.layer.cornerRadius = 25;
        _btn.backgroundColor = SQColor3DA59D;
    }
    return _btn;
}

- (UILabel *)nameLabel{
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc]init];
        _nameLabel.font = FONT_MEDIUM(16);
        _nameLabel.textColor = UIColor.blackColor;
        _nameLabel.backgroundColor = UIColor.clearColor;
        _nameLabel.numberOfLines = 0;
        _nameLabel.text = [UserModel share].name;
    }
    return _nameLabel;
}

- (HeaderView *)headerView{
    if (!_headerView) {
        _headerView = [[HeaderView alloc]init];
        _headerView.headerImage.contentMode = UIViewContentModeScaleAspectFill;
        _headerView.clipsToBounds = YES;
        _headerView.layer.borderWidth = 2;
        _headerView.layer.borderColor = UIColor.whiteColor.CGColor;
        _headerView.layer.cornerRadius = 34;
        _headerView.layer.masksToBounds = YES;
        [_headerView.headerImage sd_setImageWithURL:SQURLImage([UserModel share].portrait)];
    }
    return _headerView;
}
@end
